#By Daoyu 2010-07-10
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.db.models import Q
from django.contrib.auth.models import User

import os

from uncle.project.models import *
from uncle.util.page import *
from uncle.util.util import *
from uncle.users.models import *
from uncle.util.util import match_email_address

pre = '/home/b25476/uncle/'

#===============================================================================
# 
#===============================================================================
def get_artist_video(request, p_id, artist_id):
    videos = video.objects.filter(user__id=artist_id)
    return render_to_response('project/set_artist_video.html',
            {'videos':videos, 'project_id':p_id, 'artist_id':artist_id, },
            context_instance=RequestContext(request))

def set_artist_project_video(request, p_id, art_id):
    pa = Project_artist.objects.filter(project__id=p_id).filter(artist__id=art_id)[0]
    
    if request.GET.has_key('movie'):
        pa.video = request.GET['movie']
    
    pa.save()
    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# New a project.
#-------------------------------------------------------------------------------
@login_required
def new_project(request):
    if request.method == 'GET':
        clients = User.objects.filter(Q(user_permissions__codename='is_client'))

        files = range(0, 3)

        return render_to_response('project/new.html',
            { 'files':files, 'clients':clients},
            context_instance=RequestContext(request))
    elif request.method == 'POST':
        obj = Project()
        obj.name = request.POST['p_name']
        obj.brand = request.POST['p_brand']
        obj.city = request.POST['p_city']
        obj.creator = request.user
      
        if request.POST['client'] != '':
            obj.client = User.objects.get(id=request.POST['client'])
            
        else:
            u_n = request.POST['username']
            company = request.POST['company']
            pwd = request.POST['pwd']
            email = request.POST['email']
            if not match_email_address(email):
                email = ''
            
            if request.POST['username']=='':
                request.user.message_set.create(message='Please select a client or create a new one.')
                return HttpResponseRedirect('/project/new/')
            elif User.objects.filter(username=request.POST['username']):
                request.user.message_set.create(message='User name already exists.')
                return HttpResponseRedirect('/project/new/')
                
            user = User()
            user.username = u_n
            user.set_password(pwd)
            user.save()
        
            
            user.email = email
            user.user_permissions.add(Permission.objects.get(codename='is_client'))
            user.save()
            
            up = User_profile()
            up.user = user
            up.company = company
            up.save()
            
            obj.client = user            
            
        obj.description = request.POST['description']
        obj.save()

        request.user.message_set.create(message='New project created.')
        return HttpResponseRedirect('/project/' + str(obj.id) + '/')

#-------------------------------------------------------------------------------
# Show all the projects.
#-------------------------------------------------------------------------------
@login_required
def all_project(request):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    if request.method == 'GET':
        projects = Project.objects.all()
        _projects = split_into_pages(request, projects)

        return render_to_response('project/all.html',
            {'projects':_projects, },
            context_instance=RequestContext(request))

@login_required
def detail(request, p_id):
    obj = Project.objects.filter(id=p_id)
    clients = User.objects.filter(Q(user_permissions__codename='is_client'))
    if not obj:
        return HttpResponseRedirect('/403/?msg=Project does not exist!')
    
    pces = Project_client_email.objects.filter(project__id=p_id)
    
    baskets = Basket.objects.filter(project__id = p_id)

    attachs = baskets.filter(type = 2)
    videos = baskets.filter(type = 0)
    youtubes = baskets.filter(type = 4)
    webpages = baskets.filter(type = 3)
    images = baskets.filter(type = 1)

    return render_to_response('project/detail.html',
            {'project':obj[0], 'pces':pces, 'attachs':attachs, 'videos':videos,
             'images': images, 'webpages':webpages, 'youtubes':youtubes,
              },
            context_instance=RequestContext(request))
    
#-------------------------------------------------------------------------------
# Edit the description of a project.
#-------------------------------------------------------------------------------
@login_required
def edit(request, p_id):    
    obj = Project.objects.filter(id=p_id)
    if not obj:
        return HttpResponseRedirect('/403/?msg=Project does not exist!')
    
    baskets = Basket.objects.filter(project__id = p_id)

    attachs = baskets.filter(type = 2)
    videos = baskets.filter(type = 0)
    youtubes = baskets.filter(type = 4)
    webpages = baskets.filter(type = 3)
    images = baskets.filter(type = 1)
    
    pces = Project_client_email.objects.filter(project__id=p_id)

    return render_to_response('project/detail_edit.html',
            {'project':obj[0], 'pces':pces, 'attachs':attachs, 'videos':videos, 'youtubes':youtubes,
             'images': images, 'webpages':webpages,
              },
            context_instance=RequestContext(request))

#-------------------------------------------------------------------------------
# Save the changes to the project's description.
#-------------------------------------------------------------------------------
@login_required
def save(request, p_id):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    if request.method == 'POST':
        obj = Project.objects.filter(id=p_id)
        if not obj:
            return HttpResponseRedirect('/403/?msg=Project does not exist!')

        obj[0].description = request.POST['description']

        obj[0].save()
        request.user.message_set.create(
            message='Description updated.')

        return HttpResponseRedirect('/project/' + str(obj[0].id) + '/edit/')

#-------------------------------------------------------------------------------
# Delete the project with id = p_id
#-------------------------------------------------------------------------------
@login_required
def delete(request, p_id):
    if request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id:
        Project.objects.filter(id=p_id).delete()

        request.user.message_set.create(
            message='Project deleted.')

    return HttpResponseRedirect('/project/all/')

#-------------------------------------------------------------------------------
# Add a new youtube URL to project.
#-------------------------------------------------------------------------------
def add_youtube(request, p_id):
    if request.method == 'POST':
        obj = Project.objects.filter(id=p_id)
        if obj:
            youtube = request.POST['new_youtube']
            youtube_text = request.POST['you_text']      # Kalle: text-field added
            youtube_title = request.POST['you_title']
            show = request.POST['youtube_show']      # Kalle: Show-field
            youtube = youtube.split('&')[0]
            youtube = youtube.split('v=')[-1]



    #        if request.POST.has_key('you_txt'): # for each text description of the file.
    #            py.text = request.POST['you_txt']


            

            py = Project_youtube()
            py.youtube = youtube
            py.youtube_title = youtube_title                      # Kalle: text-field added
            py.youtube_text = youtube_text 
            py.show = show  
            py.project = obj[0]
            
            # By Ruilin: add youtube as a video
            vi = video()
            vi.user = User.objects.get(username="moods")
            vi.title = youtube_title
            vi.text = youtube_text
            vi.movie = youtube
            vi.save()

            py.save()
            request.user.message_set.create(message='Youtube URL added.')

    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# Change the project's name
#-------------------------------------------------------------------------------
def change_project_name(request, p_id):
    if request.method == 'POST':
        project = Project.objects.filter(id=p_id)
        if project:
            project[0].name = request.POST['project_name']
            project[0].brand = request.POST['project_brand']
            project[0].city = request.POST['project_city']
            project[0].save()
            
            request.user.message_set.create(message='Project information updated')
    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
#  Add client's email to project.
#-------------------------------------------------------------------------------
def add_client_email(request, p_id):    
    if request.method == 'POST':
        project = Project.objects.filter(id=p_id)
        if project:
            email = request.POST['client_email']
            name = request.POST['client_name']           # Kalle: name-field added
            title = request.POST['client_title']         # Kalle: title-field added
            if match_email_address(email):
                pce = Project_client_email()
                pce.project = project[0]
                pce.email = email
                pce.name = name         # Kalle: name-field added
                pce.title = title       # Kalle: title-field added
                pce.save()
                
                request.user.message_set.create(message='Client e-mail added.')
            else:
                request.user.message_set.create(message='Please input a valid e-mail address.')
    
    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# 
#-------------------------------------------------------------------------------
def delete_client_email(request, p_id, e_id):
    if request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id:
        Project_client_email.objects.filter(id=e_id).delete()
        request.user.message_set.create(message='E-mail client deleted.')

    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')
